package cn.fss.business.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;

import cn.fss.common.annotation.Log;
import cn.fss.common.constant.HttpStatus;
import cn.fss.common.core.controller.BaseController;
import cn.fss.common.core.domain.AjaxResult;
import cn.fss.common.enums.BusinessType;
import cn.fss.business.domain.FssFile;
import cn.fss.business.service.IFssFileService;
import cn.fss.common.utils.poi.ExcelUtil;
import cn.fss.elasticsearch.domain.DocumentObj;
import cn.fss.elasticsearch.domain.SearchReq;
import cn.fss.elasticsearch.service.ISearchSerice;
import cn.fss.common.core.page.TableDataInfo;

/**
 * 文件信息Controller
 * 
 * @author fss
 * @date 2025-02-26
 */
@RestController
@RequestMapping("/business/file")
public class FssFileController extends BaseController
{
    @Autowired
    private IFssFileService fssFileService;
    
    @Value("${upload.filedir:}")
    private String uploadPath;
    
    
    @Value("${upload.fileweburl:}")
    private String fileweburl;//合同内容预览时访问的nginx路径
    
    @Autowired
    private ISearchSerice searchService;

    /**
     * 查询文件信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(FssFile fssFile)
    {
        startPage();
        List<FssFile> list = fssFileService.selectFssFileList(fssFile);
        return getDataTable(list);
    }

    /**
     * 导出文件信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:file:export')")
    @Log(title = "文件信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FssFile fssFile)
    {
        List<FssFile> list = fssFileService.selectFssFileList(fssFile);
        ExcelUtil<FssFile> util = new ExcelUtil<FssFile>(FssFile.class);
        util.exportExcel(response, list, "文件信息数据");
    }

    /**
     * 获取文件信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(fssFileService.selectFssFileById(id));
    }

    /**
     * 新增文件信息
     */
    @PreAuthorize("@ss.hasPermi('business:file:add')")
    @Log(title = "文件信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FssFile fssFile)
    {
    	fssFile.setCreateBy(getUsername());
        return toAjax(fssFileService.insertFssFile(fssFile));
    }

    /**
     * 修改文件信息
     */
    @PreAuthorize("@ss.hasPermi('business:file:edit')")
    @Log(title = "文件信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FssFile fssFile)
    {
    	fssFile.setUpdateBy(getUsername());
        return toAjax(fssFileService.updateFssFile(fssFile));
    }

    /**
     * 删除文件信息
     */
    @PreAuthorize("@ss.hasPermi('business:file:remove')")
    @Log(title = "文件信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(fssFileService.deleteFssFileByIds(ids));
    }
    
    @PreAuthorize("@ss.hasPermi('business:file:upload')")
    @PostMapping("/upload")
	public AjaxResult upload(MultipartFile file, Integer id) throws Exception {

    	if(file==null) {
    		return AjaxResult.error("上传内容不能为空！");
    	}
    	
    	FssFile c =fssFileService.selectFssFileById(id);
		if(c==null) {
			return AjaxResult.error("数据异常，文件记录不存在！");
			
		}
    	//获取租户
    	
    	String subpath = File.separator+"file"+File.separator+id+ File.separator;
    	String path = uploadPath +subpath;
    	File d = new File(path);
    	if(!d.exists()) {
    		d.mkdirs();
    	}
    	
    	String filename = file.getOriginalFilename();
    	File dest = new File(path+filename);
    	try {
    		file.transferTo(dest);
    	}catch(Exception ex) {
    		return AjaxResult.error(ex.getMessage());
    	}
    	//文件保存成功后，上传到es
    	String fileFormat = FilenameUtils.getExtension(dest.getName());
    	DocumentObj data = new DocumentObj();
    	data.setDocId(id);
//    	data.setUserId();
    	data.setDocName(filename);
    	data.setDocType(c.getCatelog());
    	data.setTitle(c.getTitle());
    	data.setContent(getFileBase64(dest));
    	
    	Boolean rst = searchService.uploadFile(data);
//    	boolean rst = searchService.deleteDocumnet("docwrite", "BE40D28E45E54E9D9C62C1E958675EDA");
    	if(rst) {
    		//文件上传到es成功后，再更新
    		String webpath = fileweburl+subpath+filename;
    		FssFile cc = new FssFile();
    		cc.setId(c.getId());
    		cc.setUrl(path);
    		cc.setWebUrl(webpath);
    		cc.setFileFormat(fileFormat);
    		fssFileService.updateFssFile(cc);
    		return AjaxResult.success();
    	}else {
    		//如果失败，则删除上传的文件
    		try {
    			dest.delete();
    		}catch(Exception ex) {
    			logger.info(ex.getMessage(),ex);
    		}
    		return AjaxResult.error();
    	}
	}
    
    @PreAuthorize("@ss.hasPermi('business:file:download')")
    @PostMapping("/download")
	public AjaxResult download( Integer id) throws Exception {

		return AjaxResult.success();
	}
    
    private String getFileBase64(File file) {
    	Base64.Encoder base64 = Base64.getEncoder();
        String base64Str = null;
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            base64Str = base64.encodeToString(bos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return base64Str;
 
    }
    
    /**
     * 根据关键字查询
     */
    //PreAuthorize("@ss.hasPermi('business:file:list')")
    @GetMapping("/listByKeyword")
    public TableDataInfo listByKeyword(SearchReq req)
    {
    	String keyword = req.getKeyword();
    	if(StringUtils.isBlank(keyword)) {
    		TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请输入关键字");
            return rspData;
    	}
    	TableDataInfo rst = searchService.search(req);
    	if(rst==null) {
    		rst = new TableDataInfo();
    		rst.setTotal(0l);
    	}
    	rst.setCode(HttpStatus.SUCCESS);
        return rst;
    }
    
}
